package com.yoooya.base.admin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yoooya.base.model.vo.ImgResponseObj;
import com.yoooya.base.service.UploadService;
import com.yoooya.base.utils.IdUtils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @创建人 Sun Yijing
 * @创建时间 2018-06-28
 */
@Controller
@RequestMapping("/upload/")
public class UploadController {

	@Autowired
	private UploadService uploadService;
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Value("${image.server.domain}")
	private String imageServerDomain;
	@Value("${image.root.dir}")
	private String imageRootDir;
	@Value("${file.root.dir}")
	private String fileRootDir;
	@Value("${image.allow.format}")
	private String imageAllowedFormat;
	@Value("${image.max.size}")
	private Long imageMaxSize;
	// 文件允许格式
	private String[] allowFiles = { "swf", "wmv", "gif", "png", "jpg", "jpeg",
			"bmp" };

	@RequestMapping(value = "/img/{image:[a-zA-Z0-9\\\\.]+}")
	public ResponseEntity<byte[]> fetchImg(@PathVariable String image)
			throws IOException {
		File file = FileUtils.getFile(imageRootDir, "ue", image);
		return file.exists() ? new ResponseEntity<>(
				FileUtils.readFileToByteArray(file), HttpStatus.OK) : null;
	}

	@RequestMapping(value = "/up-token", method = RequestMethod.GET)
	@ResponseBody
	public Object upToken() {
		Map<String, String> map = new HashMap<String, String>();
		map.put("uptoken", uploadService.getUpToken());
		return map;
	}


	@RequestMapping(value = "/img-upload", method = { RequestMethod.POST })
	@ResponseBody
	public ImgResponseObj uploader(@RequestParam("picFile") MultipartFile file,
			@RequestParam("fileName") String fileName) {
		ImgResponseObj resp = new ImgResponseObj();
		if (file.isEmpty()) {
			resp.setState("未包含文件上传域");
		} else if (file.getSize() > imageMaxSize*20) {
			resp.setState("文件大小超出限制");
		} else {
			String originalName = file.getOriginalFilename();
			originalName = originalName.toLowerCase();
			if (FilenameUtils.isExtension(originalName, allowFiles)) {
				resp.setType(FilenameUtils.getExtension(originalName));
				Long id = IdUtils.id();
				resp.setFileName(id + "." + resp.getType());
				File path = FileUtils.getFile(imageRootDir, "ue");
				try {
					FileUtils.forceMkdir(path);
					File ordinalFile = FileUtils.getFile(path,
							resp.getFileName());
					file.transferTo(ordinalFile);
					String fileUrl = uploadService
							.upload(ordinalFile, ordinalFile.getName());
					resp.setUrl(fileUrl);
					ordinalFile.delete();
					resp.setState("SUCCESS");
					resp.setSize(file.getSize());
					resp.setOriginalName(originalName);
					resp.setRelativeUrl(resp.getUrl());

				} catch (IOException e) {
					resp.setState("上传请求异常");
					logger.error(e.getMessage(), e);
				}
			} else {
				resp.setState("不允许的文件格式");
			}
		}
		return resp;
	}

}
